// TpiNetClient.cs
//
// This file implements a Form-derived class that is also
// a remote TPI.NET client. It demonstrates how to connect
// to a remote TLA and subscribe to events raised by TPI.NET.
/////////////////////////////////////////////////////////////

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Tektronix.LogicAnalyzer.TpiNet;

namespace CSharpRemoteTpiNetApplication
{
	public class CSRemoteClient : System.Windows.Forms.Form
	{
        // Data members for controls
		private System.Windows.Forms.Label versionLabel;
        private System.Windows.Forms.Button runButton;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label eventLabel;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		// A reference to the top of the TPI.NET object hierarchy
		// in the remote TLA application
		private ITlaSystem m_system = null;

		// Event shims that are required to subscribe to
		// events raised by the remote TLA application.
		private EventRemoter runStartRemoter;
        private EventRemoter runCompleteRemoter;


		// The constructor connects to the remote TLA application and 
		// subscribes to two of the ITlaRunControl events.
		public CSRemoteClient()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			
			string version = null;
			
			// The assembly TlaNetInterfaces, which this project references,
			// contains a utility class named RemoteTlaSystem. It has a
			// Connect() static method which is used to set up a connection
			// to a remote TLA. To connect, an application configuration file
			// named TpiNetRemoteClient.config is used. This file contains
			// the information needed to configure this application to
			// communicate with a TLA running on the local host. The
			// configuration file can be modified to connect to a TLA
			// on a network.
			// NOTE: For the call to Connect() to succeed, the file
			// TpiNetRemoteClient.config must be in the same directory as
			// the application executable.
			try 
			{
			    m_system = RemoteTlaSystem.Connect("TpiNetRemoteClient.config");
			    version = m_system.SWVersion;
			}
			catch {
			    // Failed to connect.
				MessageBox.Show("Could not connect to the TLA application. Make sure the TLA application is running before starting the client application. Also make sure the configuration file is located in the executable directory.");
			    m_system = null;
			}
			if (null == m_system) {
			    versionLabel.Text = "Could not connect to TLA application";
			    runButton.Enabled = false;
			    runButton.Text = "Cannot run TLA";
			}
			else {
				// Connection was successful. Now subscribe to TPI.NET events.
				// In order to subscribe, an intermediate shim object, whose type
				// is known to the TLA, is needed. In TPI.NET, we call these 
				// shims "remoters." To subscribe to a remote TPI.NET event
				// follow these steps.
				//
				// 1 )Create a remoter object of the appropriate type (see the 
				// document "TPI.NET Remote Client Design Guide for details).
				// 
				// 2) Subscribe the remoter object to the TPI.NET event using
				// a delegate for the remoter method named OnRemoteEvent().
				//
				// 3) Subscribe a local class method to the RemoteEventOccurred 
				// event of the remoter object.
				//
				// When the subscribed TPI.NET event is raised, the TLA will
				// make a callback to the remoter object. The remoter will,
				// in turn, raise its RemoteEventOccurred event; and the local
				// event handler will be called with same arguments that the
				// TLA application passed to the remoter.
				//
				// These steps are demonstrated in the code below, which
				// subscribes to ITlaRunControl.RunStarted and
				// ITlaRunControl.RunCompleted.

				// Subscribe to ITlaRunControl.RunStarted.
				runStartRemoter = new EventRemoter();
			    m_system.RunControl.RunStarted += new EventHandler (runStartRemoter.OnRemoteEvent);
			    runStartRemoter.RemoteEventOccurred += new EventHandler (OnRunStarted);

				// Subscribe to ITlaRunControl.RunCompleted.
				runCompleteRemoter = new EventRemoter();
			    m_system.RunControl.RunCompleted += new EventHandler(runCompleteRemoter.OnRemoteEvent);
			    runCompleteRemoter.RemoteEventOccurred += new EventHandler (OnRunCompleted);
				
				versionLabel.Text = string.Format 
					("TLA Software Version is {0}", version);
				
				// Local events don't need shims.
				this.Closed += new EventHandler(OnFormClosed);
			    runButton.Click += new EventHandler(OnRunButton);
			}
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.versionLabel = new System.Windows.Forms.Label();
            this.runButton = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.eventLabel = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // versionLabel
            // 
            this.versionLabel.Location = new System.Drawing.Point(16, 24);
            this.versionLabel.Name = "versionLabel";
            this.versionLabel.Size = new System.Drawing.Size(256, 32);
            this.versionLabel.TabIndex = 0;
            this.versionLabel.Text = "label1";
            // 
            // runButton
            // 
            this.runButton.Location = new System.Drawing.Point(16, 64);
            this.runButton.Name = "runButton";
            this.runButton.Size = new System.Drawing.Size(248, 32);
            this.runButton.TabIndex = 1;
            this.runButton.Text = "Run the TLA";
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(16, 120);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(256, 24);
            this.label1.TabIndex = 2;
            this.label1.Text = "Most Recent Run Event:";
            // 
            // eventLabel
            // 
            this.eventLabel.Location = new System.Drawing.Point(16, 152);
            this.eventLabel.Name = "eventLabel";
            this.eventLabel.Size = new System.Drawing.Size(256, 32);
            this.eventLabel.TabIndex = 3;
            this.eventLabel.Text = "None.";
            // 
            // CSRemoteClient
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
            this.ClientSize = new System.Drawing.Size(292, 208);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.eventLabel,
                                                                          this.label1,
                                                                          this.runButton,
                                                                          this.versionLabel});
            this.Name = "CSRemoteClient";
            this.Text = "Remote TPI.NET Client";
            this.ResumeLayout(false);

        }
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			try {
			    Application.Run(new CSRemoteClient());
			}
			catch {
			    MessageBox.Show("The remote TPI.NET client experienced an error and must shut down.");
			}
		}
		
	// Event Handlers	

		// Event handler for the ITlaRunControl.RunStarted event.
		private void OnRunStarted(object sender, EventArgs args) 
		{
			eventLabel.Text = "An acquisition started.";
			runButton.Enabled = false;
		}
		
		
		// Event handler for the ITlaRunControl.RunCompleted event.
		private void OnRunCompleted(object sender, EventArgs args) 
		{
		    eventLabel.Text = "An acquisition completed.";
		    runButton.Enabled = true;
		}
		
		
		// Removes TPI.NET event subscriptions when the user exits the
		// application. TPI.NET clients should always clean up their
		// subscriptions before exiting.
		private void OnFormClosed(object sender, EventArgs args) 
		{
		    if (null != m_system) {
		        m_system.RunControl.RunStarted -= new EventHandler(runStartRemoter.OnRemoteEvent);
		        m_system.RunControl.RunCompleted -= new EventHandler(runCompleteRemoter.OnRemoteEvent);
		    }
		}


		// Starts a TLA acquistion when the user clicks the 
		// "Run the TLA" button.
		private void OnRunButton(object sender, EventArgs args) 
		{
		    if (null != m_system) {
		        m_system.RunControl.Run();
		    }
		}
	}
}
